<?php
/**
 * Service class for emails
 *
 * @author Ishtiaque Shahrier <md.ishtiaque@newgenbd.net>
 * @package email
 * @subpackage libraries
 */
include_once APPPATH."modules/email/libraries/swift_mailer_4_0_6/lib/swift_required.php";

class service_l_email {

    public function __construct() {
        
    }

    public function get_all_templates() {
        $obj = new templates_m_email();
        $obj->get_iterated();
        if ($obj->count()) {
            return $obj;
        } else {
            return NULL;
        }
    }

    public function get_template_by_type($type) {
        $obj = new templates_m_email();
        $obj->get_by_type($type);
        if ($obj->result_count()) {
            return $obj;
        } else {
            return NULL;
        }
    }

    public function get_template_by_id($id) {
        $obj = new templates_m_email();
        $obj->get_by_id($id);
        if ($obj->exists()) {
            return $obj;
        } else {
            return NULL;
        }
    }
    /**
     * Takes a template object nad then renders the tempalte using smarty
     *
     * @param templates_m_email $t the template we want to use for the email
     * @return string rendered html/plain text from a template
     */
    public function render_template(templates_m_email $t) {
        $o = NULL;
        if (strlen($class = $t->object_to_pass)) {
            $o = class_loader::new_obj($class);
            if (!is_a($o, "a_template_info_object_l_email")) {
                logger::i()->warning($t->object_to_pass . " is not a valid template info object", "template","email");
            }
        }
        get_instance()->smarty_wrapper->assign("obj", $o);
        get_instance()->smarty_wrapper->assign("base_url", base_url());
        return get_instance()->smarty_wrapper->stand_alone_fetch($t->get_module_name(), $t->file_name, $t->get_folder_name());
    }

    public function send_mail(email_m_email $obj, $protocol=transport_type_m_email::SMTP) {
        
        $mailer = Swift_Mailer::newInstance(transport_factory_l_email::get_transport($protocol));

        $message =      Swift_Message::newInstance()
                        ->setBcc($obj->get_bccs())
                        ->setCc($obj->get_ccs())
                        ->setSubject($obj->get_subject())
                        ->setFrom($obj->get_from())
                        ->setTo($obj->get_tos());

        if($obj->is_html()){
            $message->setBody("")->addPart($obj->get_body(),"text/html");
        }else{
            $message->setBody($obj->get_body());
        }
                        

        $num_sent = 0;
        try{
            $num_sent = $mailer->send($message);
        } catch (Exception $e){
            logger::i()->error($e->getMessage(), "send","email" );
        }
        return $num_sent;
    }

}

?>
